import React, {useContext, useReducer, useState} from 'react'

//多数情况useReducer和useContext搭配一起使用

//定义在外部的状态,的一个对象
const intialState = {
    a:1,
    b:2,
}

const reducer = (prevState, action) => {
    let newState = {...prevState}
    switch (action.type) {
        case 'hhh-a':
            newState.a=action.value
            return newState
        case 'hhh-b':
            newState.b=action.value
            return newState
        default:
            return false
    }
}

const GlobalContext=React.createContext()

export default function App() {

    const [state, dispatch] = useReducer(reducer, intialState)

    return (

        <GlobalContext.Provider className="Provider" value={
            {
                state,
                dispatch
            }
        }>
            <div style={{background: 'red'}}>
                <Child1></Child1>
                <Child2></Child2>
                <Child3></Child3>
            </div>
        </GlobalContext.Provider>


    )
}

function Child1() {
    const {dispatch}=useContext(GlobalContext)
    return (
        <div style={{background: 'yellow'}}>
            <button onClick={()=>{
                dispatch({
                    type: 'hhh-a',
                    value:'2222'
                })
            }}>改变a</button>
            <button onClick={()=>{
                dispatch({
                    type: 'hhh-b',
                    value:'3333'
                })
            }}>改变b</button>
        </div>
    )
}

function Child2() {
    const {state}=useContext(GlobalContext)
    return (
        <div style={{background:'green'}}>
            Child2-{state.a}
        </div>
    )
}

function Child3() {
    const {state}=useContext(GlobalContext)
    return (
        <div style={{background:'blue'}}>
            Child3-{state.b}
        </div>
    )
}